import { checkLoginStatus, showMessage, formatPrice } from './common.js';

// 加载订单列表
async function loadOrders(status = '') {
    const user = await checkLoginStatus();
    if (!user) {
        showMessage('warning', '请先登录');
        window.location.href = 'login.html';
        return;
    }

    try {
        const response = await orders.getByUser(user.id, 1, 10, status);
        if (response.success) {
            renderOrders(response.data);
        } else {
            showEmptyOrders();
        }
    } catch (error) {
        showMessage('error', '加载订单失败');
        showEmptyOrders();
    }
}

// 渲染订单列表
function renderOrders(orders) {
    const ordersList = document.getElementById('orders-list');
    if (!ordersList) return;

    ordersList.innerHTML = '';

    if (!orders || orders.length === 0) {
        showEmptyOrders();
        return;
    }

    orders.forEach(order => {
        const orderItem = document.createElement('div');
        orderItem.className = 'order-item';

        const statusMap = {
            1: '待支付', 2: '待发货', 3: '待收货', 4: '待评价', 5: '已完成', 6: '已取消'
        };

        orderItem.innerHTML = `
            <div class="order-header">
                <div class="order-id">订单号: ${order.id}</div>
                <div class="order-status ${getStatusClass(order.status)}">${statusMap[order.status] || '未知状态'}</div>
                <div class="order-time">${formatTime(order.createdAt)}</div>
            </div>
            <div class="order-items-preview">
                ${order.items.slice(0, 3).map(item => `
                    <div class="preview-item">
                        <img src="/uploads/products/${item.product.images?.[0] || 'default-product.jpg'}" alt="${item.product.name}">
                        <span>${item.product.name} × ${item.quantity}</span>
                    </div>
                `).join('')}
                ${order.items.length > 3 ? `<div class="more-items">+${order.items.length - 3}件商品</div>` : ''}
            </div>
            <div class="order-footer">
                <div class="order-total">实付: ${formatPrice(order.totalAmount)}</div>
                <div class="order-actions">
                    ${order.status === 1 ? `<button class="btn btn-sm btn-pay" data-id="${order.id}">去支付</button>` : ''}
                    ${order.status === 1 ? `<button class="btn btn-sm btn-cancel" data-id="${order.id}">取消订单</button>` : ''}
                    ${order.status === 3 ? `<button class="btn btn-sm btn-confirm" data-id="${order.id}">确认收货</button>` : ''}
                    <a href="order-detail.html?id=${order.id}" class="btn btn-sm btn-detail">查看详情</a>
                </div>
            </div>
        `;

        ordersList.appendChild(orderItem);
    });

    // 添加按钮事件
    document.querySelectorAll('.btn-pay').forEach(btn => {
        btn.addEventListener('click', payOrder);
    });

    document.querySelectorAll('.btn-cancel').forEach(btn => {
        btn.addEventListener('click', cancelOrder);
    });

    document.querySelectorAll('.btn-confirm').forEach(btn => {
        btn.addEventListener('click', confirmOrder);
    });
}

// 获取状态对应的CSS类
function getStatusClass(status) {
    const classMap = {
        1: 'status-pending',
        2: 'status-processing',
        3: 'status-shipped',
        4: 'status-review',
        5: 'status-completed',
        6: 'status-cancelled'
    };
    return classMap[status] || '';
}

// 支付订单
async function payOrder(e) {
    const orderId = e.target.dataset.id;
    try {
        // 模拟支付成功
        const response = await orders.update({
            id: orderId,
            status: 2, // 待发货
            paymentTime: new Date().toISOString()
        });

        if (response.success) {
            showMessage('success', '支付成功');
            loadOrders();
        }
    } catch (error) {
        showMessage('error', '支付失败');
    }
}

// 取消订单
async function cancelOrder(e) {
    const orderId = e.target.dataset.id;
    try {
        const response = await orders.cancel(orderId);
        if (response.success) {
            showMessage('success', '订单已取消');
            loadOrders();
        }
    } catch (error) {
        showMessage('error', '取消订单失败');
    }
}

// 确认收货
async function confirmOrder(e) {
    const orderId = e.target.dataset.id;
    try {
        const response = await orders.update({
            id: orderId,
            status: 4 // 待评价
        });

        if (response.success) {
            showMessage('success', '已确认收货');
            loadOrders();
        }
    } catch (error) {
        showMessage('error', '确认收货失败');
    }
}

// 显示空订单
function showEmptyOrders() {
    const ordersList = document.getElementById('orders-list');
    if (!ordersList) return;

    ordersList.innerHTML = `
        <div class="empty-orders">
            <img src="images/empty-orders.png" alt="无订单">
            <p>您还没有订单</p>
            <a href="products.html" class="btn btn-primary">去逛逛</a>
        </div>
    `;
}

// 初始化筛选按钮
function initFilterButtons() {
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            const status = this.dataset.status;
            loadOrders(status);
        });
    });
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', () => {
    loadOrders();
    initFilterButtons();
});